<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="addUsers">添加用户</el-button>
      </div>
      <el-table
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="id"
        />
        <el-table-column
          label="头像"
        >
          <template slot-scope="scope">
            <img :src="'http://api.nuzn.cn/'+scope.row.avatar" alt="" width="80px">
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
        />
        <el-table-column
          prop="title"
          label="角色分组"
        />
        <el-table-column
          min-width="150px"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
    >

      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">

        <el-form-item label="头像" prop="img">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            action
            :http-request="handleUploadForm"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="'http://api.nuzn.cn/'+imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>
        <el-form-item label="角色分组" prop="role">
          <el-select v-model="ruleForm.role" placeholder="请选择角色分组" @change="$forceUpdate()">
            <el-option v-for="v in role" :key="v.id" :label="v.title" :value="v.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onsubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { GetUserList, getRoleList, addUser, delUser, editUser } from './api/index'
import request from '@/utils/request'

export default {
  data() {
    return {
      tableData: [],
      role: [],
      imageUrl: '',
      dialogVisible: false,
      isApit: '',
      ruleForm: {
        username: '',
        password: '',
        role: '',
        img: '',
        id: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色分组', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '请上传头像', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取用户列表
    this.getuser()
    getRoleList().then(x => {
      console.log(x)
      this.role = x.data
    })
  },
  methods: {
    changes(e) {
      console.log(e)
    },
    getuser() {
      GetUserList().then(x => {
        this.tableData = x.data
      })
    },
    handleUploadForm(params) {
      const formData = new FormData()
      formData.append('file', params.file)
      request({
        url: '/api/admin/upload/img',
        method: 'post',
        data: formData
      }).then(x => {
        if (x.code == '20000') {
          this.imageUrl = x.data
          this.ruleForm.img = x.data
          this.$message({ type: 'success', message: '图片上传成功' })
        } else {
          this.$message({ type: 'error', message: '图片上传失败' })
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleEdit(index, row) {
      if (row.id == '1') {
        this.$message({ type: 'success', message: '源数据不能删除' })
        return
      }
      this.ruleForm = {}
      console.log(index, row, row.role_id)
      // this.ruleForm = row
      this.ruleForm = {
        'username': row.username,
        'id': row.id,
        'role': row.role_id,
        'img': row.avatar
      }
      // this.ruleForm.username = row.username
      // this.ruleForm.id = row.id
      // this.ruleForm.role = row.role_id
      this.imageUrl = row.avatar
      // this.ruleForm.img = row.avatar
      this.isApit = '2'
      this.dialogVisible = true
    },
    handleDelete(index, row) {
      if (row.id == '1') {
        this.$message({ type: 'success', message: '源数据不能删除' })
        return
      }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        delUser({ id: row.id }).then(x => {
          if (x.code == '20000') {
            this.$message({ type: 'success', message: '删除用户成功' })
            this.getuser()
          } else {
            this.$message({ type: 'error', message: '删除用户失败' })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })

      console.log(index, row)
    },
    addUsers() {
      this.isApit = 1
      this.dialogVisible = true
      this.ruleForm = {}
      this.imageUrl = ''
    },
    onsubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isApit == '1') {
            this.dialogVisible = false
            addUser(this.ruleForm).then(x => {
              if (x.code == '20000') {
                this.$message({ type: 'success', message: '添加用户成功' })
                this.getuser()
              } else {
                this.$message({ type: 'error', message: '添加用户失败' })
              }
            })
          } else if (this.isApit == '2') {
            this.dialogVisible = false


            this.role.forEach(x => {
              if (x.title == this.ruleForm.title) {
                this.ruleForm.title = x.id
              }
            })
            editUser(this.ruleForm).then(x => {
              console.log(x)
              if (x.code == '20000') {
                this.$message({ type: 'success', message: '修改用户成功' })
                this.getuser()
              } else {
                this.$message({ type: 'error', message: '修改用户失败' })
              }
            })
            console.log('修改')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>
